package kaituozhe.com.loadcontactdemo;

import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import org.litepal.crud.DataSupport;
import org.litepal.tablemanager.Connector;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    public static final String KEY_NUMBER = "number";

    private ListView mListView;
    private ProgressBar mProgressBar;
    private ArrayList<ContactBean> mDatas;

    private ContactSelectedAdapter mAdapter;
    private ContactBean item;
    private SQLiteDatabase mDatabase;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initEvent();
        initDataFirst();
        //建表
        if (mDatabase == null) {
            mDatabase = Connector.getDatabase();
        }
        task.execute();
    }

    AsyncTask task = new AsyncTask() {
        @Override
        protected Object doInBackground(Object[] params) {
            long l = System.currentTimeMillis();
            //查询数据
            ArrayList<ContactBean> all = (ArrayList<ContactBean>) DataSupport.findAll(ContactBean.class);
            long l1 = System.currentTimeMillis();
            Log.i("My:", "--------时间差-*****" + (l1 - l));
            return all;
        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            mDatas = (ArrayList<ContactBean>) o;
            mAdapter.notifyDataSetChanged();
        }

        @Override
        protected void onProgressUpdate(Object[] values) {
            super.onProgressUpdate(values);
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
        }
    };

    private void initDataFirst() {
//        mDatas = ContactUtils.getAllContacts(MainActivity.this);
        mAdapter = new ContactSelectedAdapter();
        mListView.setAdapter(mAdapter);// adapter--->List<数据>---->数据类型由显示决定
        // 数据初始化
    }

    private void initView() {
        mListView = (ListView) findViewById(R.id.cs_listview);
        mProgressBar = (ProgressBar) findViewById(R.id.cs_progressbar);
    }

    private void initEvent() {
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                ContactBean itemAtPosition = (ContactBean) mListView.getItemAtPosition(position);
                Log.i("my:", "----itemAtPosition-----" + itemAtPosition.getName());
                item = (ContactBean) mAdapter.getItem(position);
                mListView.setSelection(position);
                mAdapter.setDefSelect(position);
                mAdapter.notifyDataSetChanged();
                Log.i("my:", "---click----" + item.getNumber());

            }
        });

        mListView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Log.i("my:", "---------" + position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });


    }

    private void initData() {
        // 给listview设置数据
//        mAdapter = new ContactSelectedAdapter();
//        mListView.setAdapter(mAdapter);// adapter--->List<数据>---->数据类型由显示决定
        // 显示
        mProgressBar.setVisibility(View.VISIBLE);

        // 在子线程中执行数据操作
        new Thread(new Runnable() {
            @Override
            public void run() {
//                try {
//                    Thread.sleep(2000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
                // 数据初始化
                mDatas = ContactUtils
                        .getAllContacts(MainActivity.this);

                DataSupport.saveAll(mDatas);//保存数据

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mProgressBar.setVisibility(View.GONE);
                        // 更新adapter--->UI
                        mAdapter.notifyDataSetChanged();
                    }
                });
            }
        }).start();
    }

    public void delete(View v) {
        if (mDatas != null) {
            mDatas.clear();
            DataSupport.deleteAll(ContactBean.class);//把存储的数据删掉
            mDatas = null;
            mAdapter.notifyDataSetChanged();
        }
    }

    public void add(View v) {
        if (mDatas != null) {
            mDatas.clear();
//            DataSupport.deleteAll(ContactBean.class);//加载之前把数据删掉
            mAdapter.notifyDataSetChanged();
        }
        initData();
        mAdapter.notifyDataSetChanged();
    }

    public void call(View v) {

        if (mDatas == null) {
            return;
        }
        if (item != null) {
            String number = item.getNumber();
            Toast.makeText(MainActivity.this, "拨打电话。。。" + number, Toast.LENGTH_SHORT).show();
        } else {
            mAdapter.notifyDataSetChanged();
            ContactBean item = (ContactBean) mAdapter.getItem(0);
            String number = item.getNumber();
            Toast.makeText(MainActivity.this, "拨打电话。。。" + number, Toast.LENGTH_SHORT).show();
        }
    }

    private class ContactSelectedAdapter extends BaseAdapter {

        private int defItem;

        public void setDefSelect(int position) {
            this.defItem = position;
            notifyDataSetChanged();
        }


        @Override
        public int getCount() {
            if (mDatas != null) {
                return mDatas.size();
            }
            return 0;
        }

        @Override
        public Object getItem(int position) {
            if (mDatas != null) {
                return mDatas.get(position);
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = View.inflate(MainActivity.this,
                        R.layout.item_contact_selected, null);
                holder = new ViewHolder();
                convertView.setTag(holder);
                holder.ivIcon = (ImageView) convertView
                        .findViewById(R.id.item_cs_iv_icon);
                holder.tvName = (TextView) convertView
                        .findViewById(R.id.item_cs_tv_name);
                holder.tvNumber = (TextView) convertView
                        .findViewById(R.id.item_cs_tv_number);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            // 给view设置数据
            ContactBean bean = mDatas.get(position);
            holder.tvName.setText(bean.getName());
            holder.tvNumber.setText(bean.getNumber());

            Bitmap icon = ContactUtils.getContactIcon(
                    MainActivity.this, bean.getContactId());
            if (icon != null) {
                holder.ivIcon.setImageBitmap(icon);
            }

            if (defItem == position) {
                convertView.setBackgroundResource(android.R.color.holo_red_light);
            } else {
                convertView.setBackgroundResource(android.R.color.transparent);
            }
            return convertView;
        }
    }

    // viewholder中的view--》布局中的view
    static class ViewHolder {
        TextView tvName;
        TextView tvNumber;
        ImageView ivIcon;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }
}
